package com.geekgo.ladder.core.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * Parse The Configuration File
 * @author geekgo
 * @version 2016/12/19 14:01
 */
public final class PropertiesUtil extends PropertyPlaceholderConfigurer{

    private static Map<String,String> ctxPropertiesMap;

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
        super.processProperties(beanFactoryToProcess, props);
        ctxPropertiesMap = new HashMap<String,String>();
        for (Object key:props.keySet()){
            String keyStr = key.toString();
            String value = props.getProperty(keyStr);
            ctxPropertiesMap.put(keyStr,value);
        }
    }

    /**
     * Get a value based on key ,if key is not exists ,return null.
     * @param key
     * @return
     */
    public static String getString(String key){
        return ctxPropertiesMap.get(key);
    }

    /**
     * 根据key获取值
     * @param key
     * @return
     */
    public static int getInt(String key){
        return Integer.parseInt(ctxPropertiesMap.get(key));
    }

    /**
     * 根据key获取值
     * @param key
     * @param defaultValue
     * @return
     */
    public static int getInt(String key,int defaultValue){
        String value = ctxPropertiesMap.get(key);
        if(StringUtils.isBlank(value)){
            return defaultValue;
        }
        return Integer.parseInt(value);
    }

    /**
     * 根据key获取值
     * @param key
     * @param defaultValue
     * @return
     */
    public static boolean getBoolean(String key,boolean defaultValue){
        String value = ctxPropertiesMap.get(key);
        if(StringUtils.isBlank(value)){
            return defaultValue;
        }
        return new Boolean(value);
    }
}
